<script setup lang="ts">
  // GET /editor/drafts/article/id 获取草稿生成到ID；
  // GET /editor/drafts/article/{id} 获取草稿内容接口
//   POST /editor/drafts/article 新增/修改 草稿接口
//   Content-Type application/json
//   参数：
// {
//   id
//   title  标题 最长为30个字
//   content 内容 不少于50个字
// }

//   POST  /oss/editor
//   Content-Type application/formdata
//   参数:
//     file 上传图片(支持jpg,jpeg,png)
//   id 草稿id
//   type 0 文章草稿 1 文章 2 问题草稿 3 问题 4 说说 5 评论，这里传0
  import {Editor} from "@bytemd/vue-next" //https://bytemd.js.org/#options
  import gfm from '@bytemd/plugin-gfm'
  import mermaid from '@bytemd/plugin-mermaid'
  import mediumZoom from '@bytemd/plugin-medium-zoom'
  import math from '@bytemd/plugin-math-ssr'
  import breaks from '@bytemd/plugin-breaks'
  import frontmatter from '@bytemd/plugin-frontmatter'
  import highlight from '@bytemd/plugin-highlight-ssr'

  import 'bytemd/dist/index.css'
  // import {debounce} from 'lodash-es'
  // import request from '~/utils/request'
  import {TOKEN_NAME, UPLOAD_IMG_SUPPORT, UPLOAD_IMG_PREFIX} from '~/common/constants'
  const debounceTime = 2000

  const nuxtApp = useNuxtApp()
  nuxtApp.$tokenExpireJudge()
  // 写文章
  const isLoad = ref(false)
  const isArticle = ref(false)
  const editor = ref(null)
  const plugins = ref([
    gfm(),
    mermaid(),
    mediumZoom(),
    math(),
    breaks(),
    frontmatter(),
    highlight()
  ])

  const noteData = ref({
    id: '',
    title: '',
    content_md: ''
  })
  const articlePubData = ref({})
  // onMounted(async ()=>{
  //   await nextTick(getDraftDescById)
  // })
  async function getDraftDescById() {
    if (process.client) {
      let URL = location.href
      function getUrlParams(url) {
        let urlStr = url.split('?')[1]
        const urlSearchParams = new URLSearchParams(urlStr)
        const result = Object.fromEntries(urlSearchParams.entries())
        return result
      }
      const urlParams = getUrlParams(URL)
      const uid = urlParams?.id
      const hasArticleType = urlParams.type === 'article'

      let requestParams = {
        method: 'GET',
        server: true,
        key: urlParams.type === 'article' ? 'getUArticleById' : 'getDraftDescById'
      }
      if (hasArticleType) {
        isArticle.value = true
      }
      if (uid) {
        const requestUrl = hasArticleType ? `/u/article/${uid}` : `/editor/drafts/article/${uid}`
        //根据草稿id获取内容
        const {data, msg} = await nuxtApp.$request(requestUrl, requestParams).catch(e => {
          // nuxtApp.$mutual['notification'].error({
          //   content: e.message,
          //   duration: 5000
          // })
        })
        // console.log(data)
        if (data?.title) {
          noteData.value = {
            id: data.id,
            title: data.title,
            content_md: data.content
          }
          if (hasArticleType) {
            articlePubData.value = {...data}
          }
        }
      }
    }
  }
  getDraftDescById()

  // 改变文章状态
  const changeState = () => {
    let text = ""
    switch (noteData.value.state) {
      case 1:
        text = "立即发布"
        break;
      case 2:
        text = "已发布"
        break;
      case 3:
        text = "发布更新"
        break;
      default:
        break;
    }
    //改变按钮
    plugins.value = [
      gfm(),
      {
        actions: [
          {
            title: text,
            icon: text,
            position:'right',
            handler: {
              type: 'action',
              click(ctx) {
                console.log('22222')
                noteData.value.state = 2
              },
            },
          },
        ],
      }
    ]
  }


  //防抖函数
  const debounce = (func,delay) => {
    let timer = null
    return function () {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(()=>{
        func.apply(this,arguments)
      },delay)
    }
  }
  // 存草稿箱
  const save = () => {
    saveDraftBefore()
  }
  const saveContent = debounce((e: string) => {
    saveDraftBefore(e)
  },debounceTime)

  function saveDraftBefore(e?: string) {
    if (isLoad.value) {
      isLoad.value = false
      return
    }
    if (e !== undefined) noteData.value.content_md = e
    noteData.value.state = noteData.value.state === 2 ? 3 : 1
    autoSaveDraft()
  }
  // 编辑器变化
  const handleChange = (v:string) => {
    saveContent(v)
  }

  // 标题变化
  const handleInput = debounce(save,debounceTime)

  //上传图片
  const uploadImages = async (files) => {
    console.log('files',files)
    await checkNoteId()
    if (noteData.value.id) {
      //  上传图片文件
      return Promise.all(
        files.map(async (file) => {
          if (UPLOAD_IMG_SUPPORT.findIndex(item => {return item.indexOf(file.type)>-1})) {
            //   Content-Type application/formdata
            //   参数:
            //     file 上传图片(支持jpg,jpeg,png)
            //   id 草稿id
            //   type 0 文章草稿 1 文章 2 问题草稿 3 问题 4 说说 5 评论
            const formData = new FormData();
            formData.append('file', file)
            formData.append('[id].vue', noteData.value.id)
            formData.append('type', isArticle.value ? '1' : '0')
            // 处理多张图片
            // for (let i = 0; i < files.length; i++) {
            //   formData.append("images", files[i]);
            // }
            const {data, msg} = await nuxtApp.$request('/oss/editor',{
              method: 'POST',
              server: false,
              key: 'ossEditor',
              // headers: {
              //   'Content-Type': 'multipart/form-data' // 'application/form-data'
              // },
              body: formData
            }, '上传中…').catch(e => {
              // nuxtApp.$mutual['notification'].error({
              //   content: e.message,
              //   duration: 5000
              // })
            })
            if (data) {
              return {
                url: UPLOAD_IMG_PREFIX + data // "//"+ res.data
              }
            }
          } else {
            nuxtApp.$mutual['notification'].warning({
              content: `图片上传只(支持${UPLOAD_IMG_SUPPORT.join('、')})`,
              duration: 3000
            })
            return ''
          }
        })
      )
    } else {

    }
  }
  // check id & get
  const checkNoteId = async () => {
    if (noteData.value.id) {
      return noteData.value.id
    } else {
      // get
      const {data, msg} = await nuxtApp.$request('/editor/drafts/article/id',{
        method: 'GET',
        server: false,
        key: 'editorDraftsArticleId'
      }).catch(e => {
        nuxtApp.$mutual['notification'].error({
          content: e.message,
          duration: 5000
        })
      })
      if (data) noteData.value.id = data
    }
  }
  // 存
  async function autoSaveDraft(showWarn?:boolean) {
    // check id
    const warnText = noteData.value.title.length > 30 ? '标题长度不能大于30' :  noteData.value.content_md.length < 50 ? '文章内容长度小于50' : ''
    if (warnText) {
      if (showWarn) {
        nuxtApp.$mutual['notification'].warning({
          content: warnText,
          duration: 2000
        })
      }
    } else {
      await checkNoteId()
      if (noteData.value.id) {
        const saveReqData = {
          method: 'POST',
          server: false,
          key: isArticle.value ? 'uArticleSnapshot' : 'editorDraftsArticle',
          headers: {
            'Content-Type': 'application/json'
          },
          body: {
            id: noteData.value.id,
            title: noteData.value.title,
            content: noteData.value.content_md
          }
        }
        if (isArticle.value) {
          saveReqData.body.articleId = noteData.value.id
          delete saveReqData.body.id
        }
        let reqUrl = isArticle.value ? '/u/article/snapshot' : '/editor/drafts/article'
        const {data, msg} = await nuxtApp.$request(reqUrl, saveReqData, '保存中…').catch(e => {
          console.log('保存失败：e--', e)
        })
      }
    }
  }
  function updateArticle() {
    // todo 更新文章（快照）
  }
</script>

<template>
   <div class="drafts-editor">
     <div class="art-tit-area">
       <div class="ata-left">
         <n-input class="article-tit" size="large" :maxlength="30" @input="handleInput" v-model:value="noteData.title" type="text" placeholder="输入文章标题..." />
       </div>
       <div class="ata-right">
         <span class="gray"><n-spin v-if="isLoad" size="small" /><span v-else>文章将自动保存至草稿箱(内容长度大于50)</span></span>
         <NuxtLink to="/drafts" class="backLink">
           <n-button type="primary" ghost>
             草稿箱
           </n-button>
         </NuxtLink>
         <ClientOnly>
           <publish-popver :draftId="noteData.id" :isArticle="isArticle" :option="articlePubData" :editorContent="noteData.content_md"></publish-popver>
         </ClientOnly>
         <NuxtLink to="/" class="backLink">返回首页</NuxtLink>
       </div>
     </div>
     <div class="article-edit">
       <Editor
         class="editor"
         ref="editor"
         v-model:value="noteData.content_md"
         :plugins="plugins"
         @change="handleChange"
         :uploadImages="uploadImages"
       />
     </div>
   </div>
</template>

<style scoped lang="scss">
  .drafts-editor {
    display: flex;
    height: 100vh;
    flex-direction: column;
    background: #fff;
    .art-tit-area {
      display: flex;
      align-items: center;
      .ata-left {
        flex: 1;
        .article-tit {
          border: 0;
          outline: none;
          --n-border: none;
          --n-border-hover: none;
          --n-border-focus: none;
          --n-box-shadow-focus: none;
        }
      }
      .gray {
        color: #a0a0a0;
        margin-right: 10px;
      }
      .ata-right {
        button {
          margin-right: 8px;
        }
        .backLink {
          margin-right: 12px;
        }
      }
    }
    .article-edit {
      flex:1;
      display: flex;
      flex-direction: column;
      .editor {
        height: 100%;
      }
    }
  }
</style>
<style>
  .article-edit .editor .bytemd {
    height: 100%;
  }
  .n-input--focus {
    border: none;
  }
</style>
